import Action from './Action'

interface attr {
    userId?: string | number
    otherId?: string | number
    kid?: string | number
    type?: string
    firstTime?: string
    lastTime?: string
    createTime?: string
    keywords?: string
}

export default class ImChat extends Action {
    columns: any
    tableIndexArr: Array<{ name: string; key: string }>
    constructor() {
        super()
        this.tableName = 'im_chat'

        this.columns = {
            kid: 'INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL',
            id: 'BIGINT(20) NOT NULL', //聊天消息id（服务器）
            chatId: "BIGINT(20) NOT NULL DEFAULT '0'", //回答消息ID
            receiver: "BIGINT(20) NOT NULL DEFAULT '0'", //接收方id
            sender: "BIGINT(20) NOT NULL DEFAULT '0'", //发送方id
            type: 'INT(2)', //消息类型
            content: 'TEXT', //消息体
            local: 'TEXT', //对应本地文件
            isRead: "INT(2) DEFAULT '0'", //是否阅读
            createTime: 'datetime DEFAULT NULL',
            updateTime: 'datetime DEFAULT NULL',
            delFlag: "tinyint(1) NOT NULL DEFAULT '0'"
        }

        this.tableIndexArr = [
            { name: 'idx_im_chat_id', key: 'id' },
            { name: 'idx_im_chat_sender_receiver', key: '"sender", "receiver"' },
            { name: 'idx_im_chat_sender', key: 'sender' },
            { name: 'idx_im_chat_receiver', key: 'receiver' }
        ]
    }

    readStatusLastTime(userId: string, otherId: string) {
        return new Promise((resolve, reject) => {
            this.getLastTime({
                whereObj: {
                    sender: userId,
                    delFlag: 0,
                    isRead: 0,
                    receiver: otherId
                },
                selects: `min(update_time) as lastTime`
            }).then((result: any) => {
                if (result && result.length > 0) {
                    resolve(result[0].lastTime)
                } else {
                    resolve(null)
                }
            })
        })
    }

    historyTimeList({ userId, otherId, type }: attr) {
        return new Promise((resolve, reject) => {
            let typeStr = ''
            if (type) {
                typeStr = `and type = ${type}`
            }
            this.getList({
                selects: 'date(create_time) as mtime',
                where: `where ((sender = ${otherId} and receiver = ${userId}) or (sender = ${userId} and receiver = ${otherId}))
                    ${typeStr} group by mtime`
            }).then((records: any) => {
                if (records && records.length > 0) {
                    resolve(records.map((it: any) => it.mtime))
                } else {
                    resolve([])
                }
            })
        })
    }

    getChatByKid(kid: string) {
        return new Promise((resolve, reject) => {
            this.getList({
                whereObj: { kid }
            }).then((records: any) => {
                if (records && records.length > 0) {
                    resolve(records[0])
                } else {
                    resolve(null)
                }
            })
        })
    }

    async getLocalByKid(kid: string) {
        return new Promise((resolve, reject) => {
            this.getList({
                selects: `kid, id, local`,
                whereObj: { kid }
            }).then((records: any) => {
                if (records && records.length > 0) {
                    resolve(records[0])
                } else {
                    resolve(null)
                }
            })
        })
    }

    historyList({ userId, otherId, firstTime, lastTime, createTime, type, keywords }: attr) {
        return new Promise((resolve, reject) => {
            let timeCdnStr = '',
                sort = 'asc',
                limit = '',
                typeStr = '',
                keywordsStr = ''
            if (createTime) {
                timeCdnStr = `create_time >= '${createTime + ' 00:00:00'}'`
                sort = 'asc'
                limit = 'limit 15'
            }
            if (firstTime) {
                timeCdnStr = `create_time < '${firstTime}'`
                sort = 'desc'
                limit = 'limit 15'
            }
            if (lastTime) {
                timeCdnStr = `create_time > '${lastTime}'`
                sort = 'asc'
                limit = 'limit 15'
            }
            if (type) {
                typeStr = `and type = ${type}`
            }
            if (keywords) {
                keywordsStr = `and content like '%${keywords}%'`
            }

            this.getList({
                where: `where ((sender = ${otherId} and receiver = ${userId}) or (sender = ${userId} and receiver = ${otherId}))
                    and ${timeCdnStr} ${typeStr} ${keywordsStr} order by create_time ${sort}, kid ${sort} ${limit}`
            }).then((brecords: any) => {
                console.log(brecords)
                if (brecords && brecords.length > 0) {
                    resolve(brecords)
                } else {
                    resolve([])
                }
            })
        })
    }

    historyListBykId({ userId, otherId, kid }: attr) {
        let select = `kid, id, chat_id as chatId, receiver, sender, type, content, local, is_read as isRead, create_time as createTime, update_time as updateTime, del_flag as delFlag`
        let a = this.executeOptions({
            model: this.QUERY_CUSTOM,
            sql: `select * from (select ${select} from im_chat where kid < ${kid} and ((sender = ${otherId} and receiver = ${userId}) or (sender = ${userId} and receiver = ${otherId})) order by create_time desc LIMIT 10)
                    UNION
                    select * from (select ${select} from im_chat where kid >= ${kid} and ((sender = ${otherId} and receiver = ${userId}) or (sender = ${userId} and receiver = ${otherId})) order by create_time asc LIMIT 10)`
        })
        return this.execute(a)
    }
}
